package com.thread;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

import com.http.HTTPRequester;
import com.http.HTTPResult;
import com.interf.Constant;
import com.interf.IRemoteRequester;

public class RequestHandler {
	private String mHostName;
	public ArrayList<HTTPResult> results;

	
	public RequestHandler(String hostName) {
		mHostName = hostName;
		results = new ArrayList<HTTPResult>();
	}
	
	public void SendHTTPRequests(int numThread, String[] hostNames, String address, 
			long[] offsetTimes, long timetoTest
			) {
		ExecutorService eservice = Executors.newFixedThreadPool(hostNames.length);
	    ArrayList<FutureTask<HTTPResult>> arrFutureTask = new ArrayList<FutureTask<HTTPResult>>();
		
		HTTPRequester task = new HTTPRequester(address, mHostName);
		for (int i = 0; i < hostNames.length; i++) {
			arrFutureTask.add((FutureTask<HTTPResult>) eservice.submit(new ThreadHTTPRequester(task, hostNames[i], numThread
					, offsetTimes[i], timetoTest)));
		}
		
		eservice.shutdown();
		
	    try {
	    	  	eservice.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
	  			for (FutureTask<HTTPResult> futureTask : arrFutureTask) {
					results.add(futureTask.get());
				}
	    }
	    catch (Exception e) {
	    	  e.printStackTrace();
	    }
	}
}
